package controllers

import (
	"fmt"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"github.com/eclipse/paho.mqtt.golang"
	"smart_home/mqtt/system"
	"strings"
	"time"
)

type CommandDoneController struct {
	system.Controller
}

func (c *CommandDoneController) Exece(client mqtt.Client, message mqtt.Message, clientId string) {
	result := 1
	url := "http://%s/v2/mqtt/confirm"
	strs := strings.Split(string(message.Payload()), "@")
	if len(strs) != 2 {
		result = 0
		logs.Error("command done fail")
		goto SendResult
	}

	url = fmt.Sprintf(url, strs[1])
	if _, err := httplib.Post(url).Body(string(message.Payload())).Response(); err != nil {
		logs.Error(err)
		result = 0
		goto SendResult
	}

SendResult:
	topic := clientId + "/command/result"
	data := `{"time":"%d", "done":"%s", "result":%d}`
	t := client.Publish(topic, 1, false, fmt.Sprintf(data, time.Now().Unix(), string(message.Payload()), result))
	if t.Error() != nil {
		logs.Error(t.Error())
	}
}
